﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;

namespace LunchRoller.Repositories
{
    public abstract class FileRepository<TValue> : Repository<TValue>, LunchRoller.Repositories.IFileRepository
    {
        protected FileRepository(string fileName)
        {
            _fileName = fileName;
            var ust = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
            var dir = System.IO.Path.GetDirectoryName(fileName);
            if (!ust.DirectoryExists(dir)) ust.CreateDirectory(dir);
            if (ust.FileExists(fileName))
            {

                try
                {

                    using (var fs = new System.IO.IsolatedStorage.IsolatedStorageFileStream(fileName, FileMode.Open, FileAccess.Read, ust))
                    {

                        InitData(fs);

                    }


                }
                catch (Exception ex)
                {

                    ust.DeleteFile(_fileName);
                }

            }
        }

        protected string _fileName;


        protected abstract void InitData(Stream stream);






        //public abstract IAsyncResult BeginSaveAll(AsyncCallback callback, object AsyncState);

        //public abstract IAsyncResult EndSaveAll(IAsyncResult asyncResult);

        public void SaveAll()
        {
            var ust = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
            var dir = System.IO.Path.GetDirectoryName(_fileName);
            if (!ust.DirectoryExists(dir)) ust.CreateDirectory(dir);

            using (var fs = new System.IO.IsolatedStorage.IsolatedStorageFileStream(_fileName, FileMode.Create, FileAccess.Write, ust))
            {

         
                WriteAllToStream(fs);
            }
        }
        protected abstract void WriteAllToStream(Stream stream);

    }
}
